package com.huatech.core.amqp;

import javax.annotation.PostConstruct;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import com.huatech.core.domain.User;

//@Component
public class UserTransProducer implements RabbitTemplate.ReturnCallback{

	private static final Logger LOGGER = LoggerFactory.getLogger(UserTransProducer.class);
	@Autowired
	private RabbitTemplate rabbitTemplate;

	@PostConstruct
	private void init() {
		rabbitTemplate.setReturnCallback(this);
		// 激活rabbitTemplate对象事务处理功能
		rabbitTemplate.setChannelTransacted(true);
	}

	// 开启事务支持
	@Transactional(transactionManager = "rabbitTransactionManager")
	public void send(User user) {
		LOGGER.info("Sender : {}", user.toString());
		CorrelationData cd = new CorrelationData(user.getUuid());
		rabbitTemplate.convertAndSend(RabbitConstant.EXCHANGE_DIRECT, RabbitConstant.QUEUE_USER, user, cd);
		if(true){// 出现异常时可回滚
			throw new RuntimeException("some exception");
		}
	}

	@Override
	public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
		
		LOGGER.info("returnCallback exchange:{}, routingKey:{}, replyCode:{},  replyText: ", exchange, routingKey,
				replyCode, replyText);
	}

}
